import time
from PV_Factory import PV_Factory as pf
from os.path import isfile, isdir
from config import get_config
from os import mkdir
from numpy import asarray, delete, append

if isfile("./config.py"):
    from config import get_config

if not isdir("output"):
    mkdir("output")

pv_datas = get_config()["PV"]
others_datas = get_config()["others"]

newfileFlag = False

file_name = ""

# Xdata = 0
# X_data = asarray([])
# RF1_data = asarray([])
# RF2_data = asarray([])
# RF3_data = asarray([])
# RF4_data = asarray([])
# count = others_datas["数据大小"]

# def data_display():
#     global Xdata, X_data, RF1_data, RF2_data, RF3_data, RF4_data
#     if len(X_data) >= count:
#         X_data = delete(X_data, 0)
#     if len(RF1_data) >= count:
#         RF1_data = delete(RF1_data, 0)
#     if len(RF2_data) >= count:
#         RF2_data = delete(RF2_data, 0)
#     if len(RF3_data) >= count:
#         RF3_data = delete(RF3_data, 0)
#     if len(RF4_data) >= count:
#         RF4_data = delete(RF4_data, 0)
#     X_data = append(X_data, Xdata)
#     RF1_data = append(RF1_data, pf.create_pv(pv_datas["RF_IN1"]).get())
#     RF2_data = append(RF2_data, pf.create_pv(pv_datas["RF_IN2"]).get())
#     RF3_data = append(RF3_data, pf.create_pv(pv_datas["RF_IN3"]).get())
#     RF4_data = append(RF4_data, pf.create_pv(pv_datas["RF_IN4"]).get())
#     pf.create_pv(pv_datas["X_Axis_Wave"]).put(X_data)
#     pf.create_pv(pv_datas["RF_IN1_Wave"]).put(RF1_data)
#     pf.create_pv(pv_datas["RF_IN2_Wave"]).put(RF2_data)
#     pf.create_pv(pv_datas["RF_IN3_Wave"]).put(RF3_data)
#     pf.create_pv(pv_datas["RF_IN4_Wave"]).put(RF4_data)
#     Xdata += 1


def data_save():
    global newfileFlag, file_name
    if pf.create_pv(pv_datas["存储数据开关"]).get() == 0:
        newfileFlag = True
    else:
        if newfileFlag:
            file_name = time.strftime("%Y%m%d%H%M%S", time.localtime())
            fp = open("./output/" + file_name + ".csv", "w")
            fp.write("时间,功率幅值,相位,清洗位置\n")
            fp.close()
            newfileFlag = False
        else:
            fp = open("./output/" + file_name + ".csv", "a")
            fp.write(
                time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                + ","
                # + str(pf.create_pv(pv_datas["功率幅值"]).get())
                # + ","
                # + str(pf.create_pv(pv_datas["相位"]).get())
                # + ","
                + str(pf.create_pv(pv_datas["激励状态"]).get())
                + "\n"
            )
            fp.close()
